import base64
import os
import uuid
from werkzeug.utils import secure_filename

import pymysql
from flask import Flask, jsonify,request, send_from_directory
from flask_cors import CORS  # 导入 flask_cors
import hashlib
import requests
import json
import _thread as thread
import hmac
from urllib.parse import urlparse, urlencode
from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time
import ssl
import websocket
from app_routes import register_recommendation_routes
app = Flask(__name__)

# 创建上传文件夹 - 确保目录存在
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
os.makedirs(os.path.join(UPLOAD_FOLDER, 'avatars'), exist_ok=True)
os.makedirs(os.path.join(UPLOAD_FOLDER, 'clothes'), exist_ok=True)
print(f"上传目录已创建: {UPLOAD_FOLDER}")
print(f"头像目录: {os.path.join(UPLOAD_FOLDER, 'avatars')}")
print(f"衣物目录: {os.path.join(UPLOAD_FOLDER, 'clothes')}")  # 添加衣物目录日志

# 配置允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}

# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 配置 CORS，允许前端地址访问后端
#CORS(app, resources={r"/api/*": {"origins": "http://localhost:5173"}})  # 配置前端的地址
#CORS(app, resources={r"/api/*": {"origins": "*"}})  # 配置前端的地址
CORS(app, resources={r"/*": {"origins": "*", "methods": ["GET", "POST", "PUT", "DELETE"]}})

# 数据库配置
DBHOST = "localhost"
DBUSER = "root"
DBPASS = "yunxi246810"
DBNAME = "double_create"

# 初始化 Flask 应用
app = Flask(__name__)
#获取衣物数据
def get_clothes_data():
    try:
        # 连接数据库
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor(pymysql.cursors.DictCursor)

        # 查询所有衣服数据
        query_clothes = "SELECT * FROM clothes"
        cursor.execute(query_clothes)
        clothes = cursor.fetchall()

        # 遍历每件衣服，获取其标签
        for item in clothes:
            # 查询当前衣服的标签
            query_tags = "SELECT name FROM tags WHERE clothes_id = %s"
            cursor.execute(query_tags, (item['clothes_id'],))
            tags = cursor.fetchall()
            tags = [tag['name'] for tag in tags]  # 提取标签名称

            # 将标签信息添加到衣物数据中
            item['tags'] = tags

        # 关闭数据库连接
        conn.close()

        return clothes
    except pymysql.Error as e:
        print(f"数据库连接失败: {e}")
        return []

# 提供接口获取衣服数据
@app.route('/api/clothes', methods=['GET'])
def get_clothes():
    clothes = get_clothes_data()
    return jsonify(clothes)
#插入新标签
@app.route('/api/clothes/<int:clothes_id>/tags', methods=['POST'])
def add_tag(clothes_id):
    try:
        tag = request.json.get('tag')
        if not tag:
            return jsonify({"error": "标签不能为空"}), 400

        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()
        # 插入新标签
        query = "INSERT INTO tags (clothes_id, name) VALUES (%s, %s)"
        cursor.execute(query, (clothes_id, tag))
        conn.commit()

        conn.close()
        return jsonify({"message": "标签添加成功"}), 200
    except pymysql.Error as e:
        print(f"数据库连接失败: {e}")
        return jsonify({"error": "数据库连接失败"}), 500

#删除标签
@app.route('/api/clothes/<int:clothes_id>/tags', methods=['DELETE'])
def delete_tag(clothes_id):
    try:
        tag = request.json.get('tag')
        if not tag:
            return jsonify({"error": "标签不能为空"}), 400

        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 删除标签
        query = "DELETE FROM tags WHERE clothes_id = %s AND name = %s"
        cursor.execute(query, (clothes_id, tag))
        conn.commit()

        conn.close()
        return jsonify({"message": "标签删除成功"}), 200
    except pymysql.Error as e:
        print(f"数据库连接失败: {e}")
        return jsonify({"error": "数据库连接失败"}), 500

def get_user_by_username(username):
    try:
        # 连接数据库
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor(pymysql.cursors.DictCursor)

        # 查询 user_info 表中的用户
        query = "SELECT * FROM user_info WHERE username = %s"
        cursor.execute(query, (username,))
        user = cursor.fetchone()
        conn.close()

        # 检查是否查询到用户
        if user is None:
            print(f"未找到用户名为 {username} 的用户")
            return None

        # 检查返回的用户数据是否包含 'password' 字段
        if 'password' not in user:
            print(f"用户名为 {username} 的用户数据缺少密码字段")
            return None

        return user
    except pymysql.MySQLError as e:
        print(f"数据库连接失败: {e}")
        return None
# 密码加密处理（这里使用 SHA256 示例）
def hash_password(password):
    return hashlib.sha256(password.encode('utf-8')).hexdigest()
# 用户注册接口
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()  # 获取前端传递的数据
    username = data.get('username')
    password = data.get('password')

    # 检查用户名是否已存在
    existing_user = get_user_by_username(username)
    if existing_user:
        return jsonify({"message": "用户名已存在"}), 400

    # 对密码进行加密
    hashed_password = hash_password(password)

    # 保存新用户信息
    try:
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 插入用户信息
        query_user_info = "INSERT INTO user_info (username, password) VALUES (%s, %s)"
        cursor.execute(query_user_info, (username, hashed_password))

        # 获取刚插入的user_id
        user_id = cursor.lastrowid

        # 插入默认身体测量信息
        query_body_measurements = """
        INSERT INTO body_measurements 
        (user_id, region, age, height, weight, brand, size, skin_color, face_color, 
        hair_color, hair_quality, eye_color, nickname, gender) 
        VALUES 
        (%s, 120101, 20, 165, 55, '李宁', 'S', '黄皮偏白', '双颊正面略显红', 
        '黑发为主略显棕黄', '亮泽且发丝细软', '黑棕', '', '女')
        """
        cursor.execute(query_body_measurements, (user_id,))

        # 提交事务
        conn.commit()
        conn.close()

        return jsonify({"message": "注册成功"}), 201

    except pymysql.MySQLError as e:
        print(f"数据库连接失败: {e}")
        return jsonify({"message": "注册失败"}), 500

#用户重置密码
@app.route('/api/forget_register', methods=['POST'])
def forget_register():
    # 获取前端请求数据
    data = request.get_json()
    username = data.get('username')
    new_password = data.get('password')

    # 校验必填字段
    if not username or not new_password:
        return jsonify({"message": "用户名和新密码不能为空"}), 400

    try:
        # 连接数据库
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 检查用户名是否存在
        check_user_query = "SELECT user_id FROM user_info WHERE username = %s"
        cursor.execute(check_user_query, (username,))
        user = cursor.fetchone()

        if not user:
            return jsonify({"message": "用户名不存在"}), 404

        # 加密新密码
        hashed_new_password = hash_password(new_password)

        # 更新密码
        update_query = "UPDATE user_info SET password = %s WHERE username = %s"
        cursor.execute(update_query, (hashed_new_password, username))
        conn.commit()
        conn.close()

        return jsonify({"message": "密码重置成功"}), 201

    except pymysql.MySQLError as e:
        print(f"数据库错误: {e}")
        return jsonify({"message": "密码重置失败"}), 500
# 用户登录
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()  # 获取前端传递的数据
    username = data.get('username')
    password = data.get('password')
    # 获取用户信息
    user = get_user_by_username(username)

    if user is None:
        return jsonify({"message": "用户不存在或数据有误"}), 404

    # 验证密码
    hashed_password = hash_password(password)
    print(f"输入的密码：{password}")
    print(f"加密后的密码：{hashed_password}")
    print(f"数据库中的密码：{user['password']}")

    if user['password'] != hashed_password:
        return jsonify({"message": "密码错误"}), 401

    # 登录成功
    return jsonify({
        "message": "登录成功",
        "user": {
            "username": user['username'],
            "user_id": user['user_id']  # 添加 user_id
        }
    }), 200


@app.route('/api/submit', methods=['POST'])
def submit_measurements():
    try:
        data = request.get_json()
        print("接收到的原始数据:", data)

        # 1. 验证必填字段
        if 'userId' not in data or not data['userId']:
            return jsonify({"status": "error", "message": "user_id 为必填字段"}), 400

        # 2. 构建数据字典并过滤空值
        raw_measurement_data = {
            "user_id": data["userId"],
            "nickname": data.get("nickname"),
            "region": data.get("region[2]"),
            "age": data.get("age"),
            "height": data.get("height"),
            "weight": data.get("weight"),
            "brand": data.get("brand"),
            "size": data.get("size"),
            "skin_color": data.get("skinColorText"),
            "face_color": data.get("faceColorText"),
            "hair_color": data.get("hairColorText"),
            "hair_quality": data.get("hairQualityText"),
            "eye_color": data.get("eyeColorText"),
            "gender": data.get("gender")
        }

        # 3. 过滤空值并处理数据类型
        measurement_data = {}
        for key, value in raw_measurement_data.items():
            # 空值过滤条件（可根据需求调整）
            if value not in [None, "", 0, "0", "undefined"]:
                # 数值类型处理
                if key in ['age', 'height', 'weight']:
                    try:
                        measurement_data[key] = float(value) if '.' in str(value) else int(value)
                    except:
                        print(f"字段 {key} 数值转换失败，保持原值")
                        measurement_data[key] = value
                else:
                    measurement_data[key] = value

        print("过滤后的有效数据:", measurement_data)

        # 4. 如果没有可更新字段
        if len(measurement_data) <= 1:  # 只有 user_id 时
            return jsonify({"status": "success", "message": "无有效更新字段"}), 200

        # 5. 动态生成 SQL
        set_clauses = []
        params = {"user_id": measurement_data["user_id"]}

        for field in measurement_data:
            if field != "user_id":
                set_clauses.append(f"{field} = %({field})s")
                params[field] = measurement_data[field]

        sql = f"""
        UPDATE body_measurements
        SET {', '.join(set_clauses)}
        WHERE user_id = %(user_id)s
        """

        print("生成的 SQL:", sql)
        print("参数:", params)

        # 6. 执行数据库操作
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        cursor.execute(sql, params)
        affected_rows = cursor.rowcount
        conn.commit()

        return jsonify({
            "status": "success",
            "message": f"成功更新 {affected_rows} 条记录",
            "updated_fields": list(params.keys())[1:]  # 排除 user_id
        }), 200

    except pymysql.MySQLError as e:
        conn.rollback()
        error_msg = f"数据库错误: {str(e)}"
        print(error_msg)
        return jsonify({"status": "error", "message": error_msg}), 500
    except Exception as e:
        error_msg = f"服务器错误: {str(e)}"
        print(error_msg)
        return jsonify({"status": "error", "message": error_msg}), 500
    finally:
        if 'conn' in locals() and conn.open:
            cursor.close()
            conn.close()
# 获取用户数据接口
@app.route('/api/get_body_measurements', methods=['GET'])
def get_user_data():
    user_id = request.args.get('user_id')  # 获取用户ID（假设用户ID是从前端传递的）

    # 连接数据库
    conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
    cursor = conn.cursor()

    query = """
    SELECT * FROM body_measurements WHERE user_id = %s;
    """
    cursor.execute(query, (user_id,))
    user_data = cursor.fetchone()

    cursor.close()
    conn.close()

    if user_data:
        return jsonify(user_data)
    else:
        return jsonify({"message": "User not found"}), 404

#UserCenter页的昵称性别和年龄
@app.route('/api/user-info', methods=['GET'])
def get_user_info():
    # 获取当前登录的用户ID
    user_id = request.args.get('user_id')  # 假设你有一个session或token来获取user_id

    # 假设你有一个数据库查询来获取用户信息
    try:
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 获取用户信息，修改为查询body_measurements表
        query = "SELECT nickname, age, gender FROM body_measurements WHERE user_id = %s"
        cursor.execute(query, (user_id,))
        user_info = cursor.fetchone()

        conn.close()

        if user_info:
            return jsonify({
                'nickname': user_info[0],
                'age': user_info[1],
                'gender': user_info[2]
            }), 200
        else:
            return jsonify({"message": "用户信息未找到"}), 404
    except pymysql.MySQLError as e:
        return jsonify({"message": "数据库错误"}), 500

#上传头像
@app.route('/api/upload-image', methods=['POST'])
def upload_image():
    # 获取 JSON 数据
    data = request.json
    user_id = data.get('user_id')
    file_id = data.get('file_id')

    # 数据验证
    if not user_id or not file_id:
        return jsonify({"message": "用户ID或文件ID缺失"}), 400

    try:
        user_id = int(user_id)  # 确保 user_id 是整数
    except ValueError:
        return jsonify({"message": "用户ID格式错误"}), 400

    try:
        # 连接数据库
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 检查 user_info 表中是否有该用户
        cursor.execute("SELECT * FROM user_info WHERE user_id = %s", (user_id,))
        user = cursor.fetchone()

        if user is None:
            return jsonify({"message": "用户ID不存在"}), 404

        # 更新 user_info 表中的 file_id
        update_query = "UPDATE user_info SET file_id = %s WHERE user_id = %s"
        cursor.execute(update_query, (file_id, user_id))
        conn.commit()

        conn.close()

        return jsonify({"message": "文件ID上传成功并更新用户信息"}), 200
    except pymysql.MySQLError as e:
        print("数据库错误:", e)
        return jsonify({"message": f"数据库错误: {str(e)}"}), 500

#渲染头像
@app.route('/api/get-file-id', methods=['GET'])
def get_file_id():
    # 从请求中获取 user_id
    user_id = request.args.get('user_id')

    # 验证 user_id 是否存在
    if not user_id:
        return jsonify({"message": "user_id 缺失"}), 400

    try:
        conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
        cursor = conn.cursor()

        # 查询 file_id
        query = "SELECT file_id FROM user_info WHERE user_id = %s"
        cursor.execute(query, (user_id,))
        result = cursor.fetchone()  # 获取第一条记录
        print(result)
        # 关闭数据库连接
        cursor.close()
        conn.close()

        # 检查是否找到对应的 file_id
        if result and len(result) > 0:
            # 假设第一个元素是 file_id
            file_id = result[0]  # 获取元组中的第一个元素
            return jsonify({
                "message": "成功获取 file_id",
                "file_id": file_id
            }), 200
        else:
            return jsonify({"message": "未找到对应的 file_id"}), 404


    except pymysql.MySQLError as e:
        print("数据库错误:", e)
        return jsonify({"message": f"数据库错误: {str(e)}"}), 500


# 图片识别配置
IMAGE_UNDERSTANDING_URL = "wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image"
APPID = "0c598a1b"
API_SECRET = "N2QwNDZjMTE2ODhkOGU4M2NmM2E5OGE2"
API_KEY = "1b5e512768f3c5081c6430af24f15113"

# 定义服装类别
CLOTHING_CATEGORIES = {
    '上衣': ['毛衣', '衬衣', '短袖','吊带', '长袖', '外套','西装外套', '卫衣','长羽绒服','短羽绒服','大衣','冲锋衣'],
    '裤子': ['牛仔裤', '休闲裤', '运动裤', '短裤','加绒裤', '西裤','工装裤','背带裤'],
    '裙子': ['连衣裙', '半身裙','长裙','短裙','加绒裙'],
    '鞋子': ['运动鞋', '皮鞋', '凉鞋', '雪地靴','靴子','板鞋','布鞋',"高跟鞋","保暖鞋"],
    '其他': ['首饰', '帽子', '围巾','包包','墨镜','领带']
}
# 扁平化类别列表，用于验证
ALL_SUBCATEGORIES = []
for subcats in CLOTHING_CATEGORIES.values():
    ALL_SUBCATEGORIES.extend(subcats)

# 季节的可选值
SEASONS = ['春季', '夏季', '秋季', '冬季', '四季', '春秋', '春夏', '秋冬']


class ImageUnderstandingService:
    def __init__(self):
        self.answer = ""

    def on_error(self, ws, error):
        print("### error:", error)

    def on_close(self, ws, one, two):
        print(" ")

    def on_open(self, ws):
        thread.start_new_thread(self.run, (ws,))

    def run(self, ws, *args):
        data = json.dumps(self.gen_params(appid=ws.appid, question=ws.question))
        ws.send(data)

    def on_message(self, ws, message):
        data = json.loads(message)
        code = data['header']['code']
        if code != 0:
            print(f'请求错误: {code}, {data}')
            ws.close()
        else:
            choices = data["payload"]["choices"]
            status = choices["status"]
            content = choices["text"][0]["content"]
            print(content, end="")
            self.answer += content
            if status == 2:
                ws.close()

    def gen_params(self, appid, question):
        return {
            "header": {"app_id": appid},
            "parameter": {
                "chat": {
                    "domain": "imagev3",
                    "temperature": 0.5,
                    "top_k": 4,
                    "max_tokens": 2028,
                    "auditing": "default"
                }
            },
            "payload": {"message": {"text": question}}
        }

    def create_url(self, appid, api_key, api_secret, imageunderstanding_url):
        host = urlparse(imageunderstanding_url).netloc
        path = urlparse(imageunderstanding_url).path
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
        signature_sha = hmac.new(api_secret.encode('utf-8'),
                                 signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha_base64 = base64.b64encode(signature_sha).decode('utf-8')

        authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode('utf-8')

        v = {"authorization": authorization, "date": date, "host": host}
        return imageunderstanding_url + '?' + urlencode(v)

    def analyze_image(self, image_data, questions):
        self.answer = ""  # 重置答案
        ws_param = self.create_url(APPID, API_KEY, API_SECRET, IMAGE_UNDERSTANDING_URL)
        websocket.enableTrace(False)

        # 准备问题
        text = [{"role": "user", "content": str(base64.b64encode(image_data), 'utf-8'), "content_type": "image"}]
        for question in questions:
            text.append({"role": "user", "content": question})

        # 创建WebSocket连接
        ws = websocket.WebSocketApp(ws_param,
                                    on_message=self.on_message,
                                    on_error=self.on_error,
                                    on_close=self.on_close,
                                    on_open=self.on_open)
        ws.appid = APPID
        ws.question = text
        ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

        return self.answer


# 初始化服务
image_service = ImageUnderstandingService()



# 保存识别结果
@app.route('/api/save_clothes', methods=['POST'])
def save_clothes():
    try:
        # 获取用户ID和表单数据
        data = request.json
        user_id = data.get('user_id')
        if not user_id:
            return jsonify({"error": "用户ID不能为空"}), 400

        # 基础验证
        required_fields = ['category', 'color', 'image_url']
        for field in required_fields:
            if not data.get(field):
                return jsonify({"error": f"{field}不能为空"}), 400

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 插入衣物基本信息，days字段默认为NULL
                sql = """
                INSERT INTO clothes (
                    user_id, category, subcategory, color, brand, size, 
                    material, season, image_url, fit, days
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, CURDATE())
                """
                cursor.execute(sql, (
                    user_id,
                    data.get('category'),
                    data.get('subcategory'),
                    data.get('color'),
                    data.get('brand'),
                    data.get('size'),
                    data.get('material'),
                    data.get('season'),
                    data.get('image_url'),
                    data.get('fit')
                ))
                clothes_id = cursor.lastrowid

                # 处理标签
                if 'tags' in data and isinstance(data['tags'], list):
                    for tag in data['tags']:
                        if tag.strip():  # 跳过空标签
                            cursor.execute(
                                "INSERT INTO tags (clothes_id, name) VALUES (%s, %s)",
                                (clothes_id, tag.strip())
                            )

                conn.commit()

        return jsonify({
            "message": "衣物保存成功",
            "clothes_id": clothes_id
        }), 200

    except pymysql.Error as e:
        print(f"数据库错误: {e}")
        return jsonify({"error": "数据库操作失败"}), 500
    except Exception as e:
        print(f"系统错误: {e}")
        return jsonify({"error": "系统内部错误"}), 500


# 展示衣物详情
@app.route('/api/show_clothes/<int:clothes_id>')
def get_clothes_detail(clothes_id):
    try:
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 查询衣物基础信息
                sql = "SELECT * FROM clothes WHERE clothes_id = %s"
                cursor.execute(sql, (clothes_id,))
                result = cursor.fetchone()

                if not result:
                    return jsonify({"error": "衣物不存在"}), 404

                # 格式化日期字段
                if result.get('days') and isinstance(result['days'], datetime):
                    result['days'] = result['days'].strftime('%Y-%m-%d')

                # 单独查询当前衣物的标签
                query_tags = "SELECT name FROM tags WHERE clothes_id = %s"
                cursor.execute(query_tags, (clothes_id,))
                tags_result = cursor.fetchall()
                tags = [tag['name'] for tag in tags_result]  # 提取标签名称

                # 格式化数据
                data = {
                    "clothes_id": result["clothes_id"],
                    "category": result["category"],
                    "subcategory": result["subcategory"],
                    "color": result["color"],
                    "material": result["material"],
                    "size": result["size"],
                    "image_url": result["image_url"],
                    "fit": result["fit"],
                    "season": result["season"],
                    "brand": result["brand"],
                    "days": result["days"],
                    "tags": tags
                }

                return jsonify(data), 200

    except pymysql.Error as e:
        return jsonify({"error": f"数据库错误: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

# 编辑衣物详情
@app.route('/api/update_clothes', methods=['POST'])
def update_clothes():
    try:
        data = request.get_json()
        clothes_id = data['clothes_id']
        category = data['category']
        subcategory = data['subcategory']
        color = data['color']
        brand = data.get('brand', None)
        size = data['size']
        material = data['material']
        season = data['season']
        fit = data['fit']

        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                sql = """
                UPDATE clothes
                SET category = %s,
                    subcategory = %s,
                    color = %s,
                    brand = %s,
                    size = %s,
                    material = %s,
                    season = %s,
                    fit = %s
                WHERE clothes_id = %s
                """
                cursor.execute(sql, (category, subcategory, color, brand, size, material, season, fit, clothes_id))
                conn.commit()

        return jsonify({"success": True, "message": "衣物信息更新成功"}), 200

    except pymysql.Error as e:
        return jsonify({"error": f"数据库错误: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

# 分析衣物数据
@app.route('/api/clothesList', methods=['POST'])
def get_clotheslist():
    data = request.get_json()
    user_id = data.get('user_id')

    if not user_id:
        return jsonify({"message": "缺少用户ID参数"}), 400

    try:
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )
        cursor = conn.cursor()

        # 修改查询以适应days字段的DATE类型
        query = """
            SELECT 
                clothes_id,
                category,
                image_url,
                days AS original_days,
                CASE 
                    WHEN days IS NULL THEN 0
                    ELSE DATEDIFF(CURDATE(), days) 
                END AS idle_days
            FROM clothes
            WHERE user_id = %s
        """
        cursor.execute(query, (user_id,))
        clothes_data = cursor.fetchall()

        # 格式化日期字段
        for item in clothes_data:
            if item.get('original_days') and isinstance(item['original_days'], datetime):
                item['original_days'] = item['original_days'].strftime('%Y-%m-%d')

        cursor.close()
        conn.close()

        return jsonify({
            "message": "获取衣物数据成功",
            "data": clothes_data
        }), 200

    except pymysql.MySQLError as e:
        print(f"数据库操作失败: {e}")
        if 'conn' in locals():
            conn.rollback()
            conn.close()
        return jsonify({"message": "获取衣物数据失败"}), 500
    except Exception as e:
        print(f"服务器内部错误: {e}")
        if 'conn' in locals():
            conn.rollback()
            conn.close()
        return jsonify({"message": "服务器内部错误"}), 500

#穿搭推荐集成
def integrate_recommendation_system(app):
    """
    将推荐系统集成到Flask应用中

    参数:
        app: Flask应用实例
    """
    register_recommendation_routes(app)

    print("推荐系统已成功集成到应用中")
#保存反馈
# 保存反馈
@app.route('/api/submit_feedback', methods=['POST'])
def submit_feedback():
    try:
        data = request.get_json()

        # 必要字段验证
        required = ['user_id', 'outfit_id', 'clothes_ids', 'rating']
        if not all(field in data for field in required):
            return jsonify({"error": "缺少必要字段 (user_id, outfit_id, clothes_ids, rating)"}), 400

        user_id = data['user_id']
        outfit_id = data['outfit_id']
        clothes_ids = data['clothes_ids']
        rating = data['rating']

        # 验证clothes_ids是否为列表
        if not isinstance(clothes_ids, list) or len(clothes_ids) == 0:
            return jsonify({"error": "clothes_ids必须是非空列表"}), 400

        # 获取可选字段
        seasons = data.get('seasons', '')
        tags = data.get('tags', '')
        scenes = data.get('scenes', '')
        style = data.get('style', '')
        weather_info = data.get('weather_info', '{}')

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 1. 检查outfit是否存在，不存在则插入
                cursor.execute("SELECT outfit_id FROM outfits WHERE outfit_id = %s", (outfit_id,))
                outfit_exists = cursor.fetchone()

                if not outfit_exists:
                    # 插入新的outfit
                    cursor.execute(
                        "INSERT INTO outfits (outfit_id, user_id, created_at) VALUES (%s, %s, NOW())",
                        (outfit_id, user_id)
                    )

                # 2. 处理outfit_items表 - 先删除旧的关联，再插入新的
                cursor.execute("DELETE FROM outfit_items WHERE outfit_id = %s", (outfit_id,))

                # 批量插入outfit_items
                outfit_items_values = [(outfit_id, clothes_id) for clothes_id in clothes_ids]
                cursor.executemany(
                    "INSERT INTO outfit_items (outfit_id, clothes_id) VALUES (%s, %s)",
                    outfit_items_values
                )

                # 3. 修改outfit_feedback表结构，添加新字段
                try:
                    # 检查表结构是否已更新
                    cursor.execute("SHOW COLUMNS FROM outfit_feedback LIKE 'seasons'")
                    seasons_column_exists = cursor.fetchone()

                    if not seasons_column_exists:
                        # 添加新字段
                        cursor.execute("""
                            ALTER TABLE outfit_feedback 
                            ADD COLUMN seasons VARCHAR(255) DEFAULT '',
                            ADD COLUMN tags VARCHAR(255) DEFAULT '',
                            ADD COLUMN scenes VARCHAR(255) DEFAULT '',
                            ADD COLUMN style VARCHAR(255) DEFAULT '',
                            ADD COLUMN weather_info TEXT
                        """)
                        conn.commit()
                except Exception as e:
                    print(f"检查或修改表结构时出错: {e}")
                    # 继续执行，不中断流程

                # 4. 更新outfit_feedback表
                cursor.execute(
                    """
                    INSERT INTO outfit_feedback 
                    (user_id, outfit_id, rating, seasons, tags, scenes, style, weather_info, feedback_time)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW())
                    ON DUPLICATE KEY UPDATE
                    rating = VALUES(rating),
                    seasons = VALUES(seasons),
                    tags = VALUES(tags),
                    scenes = VALUES(scenes),
                    style = VALUES(style),
                    weather_info = VALUES(weather_info),
                    feedback_time = NOW()
                    """,
                    (user_id, outfit_id, rating, seasons, tags, scenes, style, weather_info)
                )

                # 5. 更新参与搭配的所有衣物的days字段为当前日期
                today = datetime.now().strftime('%Y-%m-%d')
                for clothes_id in clothes_ids:
                    cursor.execute(
                        "UPDATE clothes SET days = %s WHERE clothes_id = %s",
                        (today, clothes_id)
                    )

                conn.commit()

                return jsonify({
                    "message": "搭配保存成功",
                    "outfit_id": outfit_id
                }), 200

    except pymysql.MySQLError as e:
        print(f"数据库错误: {e}")
        if 'conn' in locals() and conn:
            conn.rollback()  # 发生异常时回滚
        return jsonify({"error": f"数据库错误: {str(e)}"}), 500
    except Exception as e:
        print(f"服务器错误: {e}")
        if 'conn' in locals() and conn:
            conn.rollback()  # 发生异常时回滚
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

# 获取历史穿搭列表
@app.route('/api/outfit_history', methods=['GET'])
def get_outfit_history():
    try:
        # 获取请求参数
        user_id = request.args.get('user_id')
        seasons = request.args.get('seasons', '')
        scenes = request.args.get('scenes', '')
        styles = request.args.get('styles', '')
        start_date = request.args.get('start_date', '')
        end_date = request.args.get('end_date', '')

        # 验证用户ID
        if not user_id:
            return jsonify({"error": "缺少用户ID"}), 400

        # 构建SQL查询
        sql = """
        SELECT o.outfit_id, o.user_id, o.created_at, 
               fb.rating, fb.seasons, fb.tags, fb.scenes, fb.style, fb.weather_info, fb.feedback_time
        FROM outfits o
        JOIN outfit_feedback fb ON o.outfit_id = fb.outfit_id
        WHERE o.user_id = %s
        """

        params = [user_id]

        # 添加筛选条件
        if seasons:
            season_list = seasons.split(',')
            placeholders = ', '.join(['%s'] * len(season_list))
            sql += f" AND ("
            for i, season in enumerate(season_list):
                if i > 0:
                    sql += " OR "
                sql += f"fb.seasons LIKE %s"
                params.append(f"%{season}%")
            sql += ")"

        if scenes:
            scene_list = scenes.split(',')
            placeholders = ', '.join(['%s'] * len(scene_list))
            sql += f" AND ("
            for i, scene in enumerate(scene_list):
                if i > 0:
                    sql += " OR "
                sql += f"fb.scenes LIKE %s"
                params.append(f"%{scene}%")
            sql += ")"

        if styles:
            style_list = styles.split(',')
            placeholders = ', '.join(['%s'] * len(style_list))
            sql += f" AND ("
            for i, style in enumerate(style_list):
                if i > 0:
                    sql += " OR "
                sql += f"fb.style LIKE %s"
                params.append(f"%{style}%")
            sql += ")"

        if start_date:
            sql += " AND fb.feedback_time >= %s"
            params.append(start_date)

        if end_date:
            sql += " AND fb.feedback_time <= %s"
            # 添加一天的时间，使得结束日期包含当天的所有时间
            params.append(end_date + " 23:59:59")

        # 按照反馈时间降序排序
        sql += " ORDER BY fb.feedback_time DESC"

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        outfits = []

        with conn:
            with conn.cursor() as cursor:
                cursor.execute(sql, params)
                results = cursor.fetchall()

                for row in results:
                    # 转换日期格式为字符串
                    if row['created_at']:
                        row['created_at'] = row['created_at'].strftime('%Y-%m-%d %H:%M:%S')
                    if row['feedback_time']:
                        row['feedback_time'] = row['feedback_time'].strftime('%Y-%m-%d %H:%M:%S')

                    outfits.append(row)

        return jsonify({
            "message": "获取历史穿搭成功",
            "outfits": outfits
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


# 获取穿搭详情
@app.route('/api/outfit_detail', methods=['GET'])
def get_outfit_detail():
    try:
        # 获取请求参数
        outfit_id = request.args.get('outfit_id')

        # 验证搭配ID
        if not outfit_id:
            return jsonify({"error": "缺少搭配ID"}), 400

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        outfit = None
        clothes_items = []

        with conn:
            with conn.cursor() as cursor:
                # 获取搭配信息
                sql = """
                SELECT o.outfit_id, o.user_id, o.created_at, 
                       fb.rating, fb.seasons, fb.tags, fb.scenes, fb.style, fb.weather_info, fb.feedback_time
                FROM outfits o
                JOIN outfit_feedback fb ON o.outfit_id = fb.outfit_id
                WHERE o.outfit_id = %s
                """
                cursor.execute(sql, (outfit_id,))
                outfit = cursor.fetchone()

                if not outfit:
                    return jsonify({"error": "搭配不存在"}), 404

                # 转换日期格式为字符串
                if outfit['created_at']:
                    outfit['created_at'] = outfit['created_at'].strftime('%Y-%m-%d %H:%M:%S')
                if outfit['feedback_time']:
                    outfit['feedback_time'] = outfit['feedback_time'].strftime('%Y-%m-%d %H:%M:%S')

                # 获取搭配中的衣物
                sql = """
                SELECT c.clothes_id, c.category, c.subcategory, c.color, c.brand, c.size, 
                       c.material, c.season, c.image_url, c.fit
                FROM outfit_items oi
                JOIN clothes c ON oi.clothes_id = c.clothes_id
                WHERE oi.outfit_id = %s
                """
                cursor.execute(sql, (outfit_id,))
                clothes_items = cursor.fetchall()

        return jsonify({
            "message": "获取搭配详情成功",
            "outfit": outfit,
            "clothes_items": clothes_items
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


# 删除穿搭
@app.route('/api/delete_outfit', methods=['POST'])
def delete_outfit():
    try:
        data = request.get_json()

        # 验证必要字段
        if not data.get('outfit_id') or not data.get('user_id'):
            return jsonify({"error": "缺少必要字段 (outfit_id, user_id)"}), 400

        outfit_id = data['outfit_id']
        user_id = data['user_id']

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 验证搭配是否属于该用户
                sql = "SELECT outfit_id FROM outfits WHERE outfit_id = %s AND user_id = %s"
                cursor.execute(sql, (outfit_id, user_id))
                if not cursor.fetchone():
                    return jsonify({"error": "无权删除此搭配或搭配不存在"}), 403

                # 删除搭配反馈
                sql = "DELETE FROM outfit_feedback WHERE outfit_id = %s"
                cursor.execute(sql, (outfit_id,))

                # 删除搭配衣物关联
                sql = "DELETE FROM outfit_items WHERE outfit_id = %s"
                cursor.execute(sql, (outfit_id,))

                # 删除搭配
                sql = "DELETE FROM outfits WHERE outfit_id = %s"
                cursor.execute(sql, (outfit_id,))

                conn.commit()

        return jsonify({
            "message": "删除搭配成功",
            "outfit_id": outfit_id
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        if 'conn' in locals() and conn:
            conn.rollback()  # 发生异常时回滚
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/check_collection', methods=['POST'])
def check_collection():
    try:
        data = request.get_json()

        # 验证必要字段
        if not data.get('user_id') or not data.get('outfit_id'):
            return jsonify({"error": "缺少必要字段 (user_id, outfit_id)"}), 400

        user_id = data['user_id']
        outfit_id = data['outfit_id']

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 检查是否已收藏
                sql = """
                SELECT collection_id 
                FROM outfit_collection 
                WHERE user_id = %s AND outfit_id = %s
                """
                cursor.execute(sql, (user_id, outfit_id))
                result = cursor.fetchone()

        return jsonify({
            "is_collected": bool(result),
            "collection_id": result['collection_id'] if result else None
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/add_collection', methods=['POST'])
def add_collection():
    try:
        data = request.get_json()

        # 验证必要字段
        required_fields = ['user_id', 'outfit_id']
        for field in required_fields:
            if not data.get(field):
                return jsonify({"error": f"缺少必要字段 ({field})"}), 400

        user_id = data['user_id']
        outfit_id = data['outfit_id']

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 验证搭配是否存在
                sql = "SELECT 1 FROM outfits WHERE outfit_id = %s"
                cursor.execute(sql, (outfit_id,))
                if not cursor.fetchone():
                    return jsonify({"error": "搭配不存在"}), 404

                # 检查是否已收藏
                sql = """
                SELECT collection_id 
                FROM outfit_collection 
                WHERE user_id = %s AND outfit_id = %s
                """
                cursor.execute(sql, (user_id, outfit_id))
                if cursor.fetchone():
                    return jsonify({"error": "该搭配已收藏"}), 400

                # 添加收藏
                sql = """
                INSERT INTO outfit_collection (
                    user_id, outfit_id, seasons, tags, 
                    scenes, style, weather_info, created_at
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, NOW())
                """
                cursor.execute(sql, (
                    user_id,
                    outfit_id,
                    data.get('seasons', ''),
                    data.get('tags', ''),
                    data.get('scenes', ''),
                    data.get('style', ''),
                    data.get('weather_info', '')
                ))
                collection_id = cursor.lastrowid
                conn.commit()

        return jsonify({
            "message": "收藏成功",
            "collection_id": collection_id
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        if 'conn' in locals() and conn:
            conn.rollback()
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/remove_collection', methods=['POST'])
def remove_collection():
    try:
        data = request.get_json()

        # 验证必要字段
        if not data.get('collection_id') and (not data.get('user_id') or not data.get('outfit_id')):
            return jsonify({"error": "缺少必要字段 (collection_id 或 user_id+outfit_id)"}), 400

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                if data.get('collection_id'):
                    # 按collection_id删除
                    sql = """
                    DELETE FROM outfit_collection 
                    WHERE collection_id = %s
                    RETURNING collection_id
                    """
                    cursor.execute(sql, (data['collection_id'],))
                else:
                    # 按user_id和outfit_id删除
                    sql = """
                    DELETE FROM outfit_collection 
                    WHERE user_id = %s AND outfit_id = %s
                    RETURNING collection_id
                    """
                    cursor.execute(sql, (data['user_id'], data['outfit_id']))

                result = cursor.fetchone()
                conn.commit()

                if not result:
                    return jsonify({"error": "收藏记录不存在"}), 404

        return jsonify({
            "message": "取消收藏成功",
            "collection_id": result['collection_id']
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        if 'conn' in locals() and conn:
            conn.rollback()
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/get_collections', methods=['POST'])
def get_collections():
    try:
        data = request.get_json()

        # 验证必要字段
        if not data.get('user_id'):
            return jsonify({"error": "缺少必要字段 (user_id)"}), 400

        user_id = data['user_id']

        # 获取数据库连接
        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 基础查询 - 移除了不存在的 o.preview_image 列
                sql = """
                SELECT 
                    c.*, 
                    GROUP_CONCAT(DISTINCT i.category) AS categories
                FROM outfit_collection c
                LEFT JOIN outfits o ON c.outfit_id = o.outfit_id
                LEFT JOIN outfit_items oi ON o.outfit_id = oi.outfit_id
                LEFT JOIN clothes i ON oi.clothes_id = i.clothes_id
                WHERE c.user_id = %s
                """
                params = [user_id]

                # 添加过滤条件
                if data.get('seasons'):
                    sql += " AND c.seasons LIKE %s"
                    params.append(f"%{data['seasons']}%")

                if data.get('scenes'):
                    sql += " AND c.scenes LIKE %s"
                    params.append(f"%{data['scenes']}%")

                if data.get('styles'):
                    sql += " AND c.style LIKE %s"
                    params.append(f"%{data['styles']}%")

                if data.get('start_date'):
                    sql += " AND c.created_at >= %s"
                    params.append(data['start_date'])

                if data.get('end_date'):
                    sql += " AND c.created_at <= %s"
                    params.append(data['end_date'] + " 23:59:59")

                # 分组和排序
                sql += " GROUP BY c.collection_id ORDER BY c.created_at DESC"

                cursor.execute(sql, params)
                collections = cursor.fetchall()

                # 格式化日期
                for col in collections:
                    if col.get('created_at'):
                        col['created_at'] = col['created_at'].isoformat()

        return jsonify({
            "collections": collections,
            "count": len(collections)
        }), 200

    except Exception as e:
        print(f"服务器错误: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500


@app.route('/api/collection_detail', methods=['GET'])
def collection_detail():
    try:
        collection_id = request.args.get('collection_id')

        if not collection_id:
            return jsonify({"error": "Missing collection_id"}), 400

        conn = pymysql.connect(
            host=DBHOST,
            user=DBUSER,
            password=DBPASS,
            database=DBNAME,
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn:
            with conn.cursor() as cursor:
                # 1. 获取收藏基本信息
                sql = """
                SELECT 
                    c.*
                FROM outfit_collection c
                WHERE c.collection_id = %s
                """
                cursor.execute(sql, (collection_id,))
                collection = cursor.fetchone()

                if not collection:
                    return jsonify({"error": "Collection not found"}), 404

                # 2. 获取穿搭反馈信息（包括评分）
                sql = """
                SELECT 
                    rating,
                    seasons,
                    tags,
                    scenes,
                    style,
                    weather_info,
                    feedback_time
                FROM outfit_feedback
                WHERE outfit_id = %s AND user_id = %s
                ORDER BY feedback_time DESC
                LIMIT 1
                """
                cursor.execute(sql, (collection['outfit_id'], collection['user_id']))
                feedback = cursor.fetchone()

                # 3. 获取衣物列表 - 移除了对不存在的 categories 表的引用
                sql = """
                SELECT 
                    cl.*
                FROM outfit_items oi
                JOIN clothes cl ON oi.clothes_id = cl.clothes_id
                WHERE oi.outfit_id = %s
                """
                cursor.execute(sql, (collection['outfit_id'],))
                clothes_items = cursor.fetchall()

                # 格式化响应数据
                response_data = {
                    "status": "success",
                    "outfit": {
                        **collection,
                        "feedback": feedback if feedback else None
                    },
                    "clothes_items": clothes_items
                }

                # 格式化日期
                if response_data['outfit'].get('created_at'):
                    response_data['outfit']['created_at'] = response_data['outfit']['created_at'].isoformat()
                if feedback and feedback.get('feedback_time'):
                    response_data['outfit']['feedback']['feedback_time'] = feedback['feedback_time'].isoformat()

        return jsonify(response_data), 200

    except Exception as e:
        print(f"Server error: {e}")
        return jsonify({
            "status": "error",
            "error": f"Server error: {str(e)}"
        }), 500


# 图片识别接口
@app.route('/api/analyze-image', methods=['POST'])
def analyze_image():
    try:
        # 检查是否有文件上传
        if 'image' in request.files:
            # 直接从请求中获取文件
            file = request.files['image']
            # 读取文件内容
            image_data = file.read()
        elif request.is_json and 'image' in request.json:
            # 兼容旧的base64方式
            data = request.get_json()
            image_data = base64.b64decode(data['image'])
        else:
            return jsonify({"message": "未上传图片"}), 400

        # 构建限制选项的问题
        subcategory_options = ", ".join(ALL_SUBCATEGORIES)
        season_options = ", ".join(SEASONS)

        # 只发送一个问题，同时询问所有属性，并明确要求简短回答
        question = (
            f"请分析图片中的服装，并回答以下问题：\n"
            f"类别（从以下选择一个）: {subcategory_options}\n"
            f"材质: (请用1-2个词简洁描述，如'棉'、'尼龙'、'牛仔'等)\n"
            f"版型: (请用1-2个词简洁描述，如'宽松'、'修身'、'直筒'等)\n"
            f"颜色: (请用1-2个词简洁描述，如'黑色'、'蓝色'、'灰色'等)\n"
            f"季节（从以下选择一个）: {season_options}\n"
            f"请按照'类别:答案\n材质:答案\n版型:答案\n颜色:答案\n季节:答案'的格式回答，每个答案只需要简短的词语，不要回答句子。"
        )

        raw_result = image_service.analyze_image(image_data, [question])
        print("原始分析结果:", repr(raw_result))  # 使用repr显示不可见字符

        # 解析结果
        result = {
            '大类': "未识别",
            '子类别': "未识别",
            '材质': "未识别",
            '版型': "未识别",
            '颜色': "未识别",
            '季节': "未识别"
        }

        # 解析每一行
        for line in raw_result.split('\n'):
            line = line.strip()
            if not line:
                continue

            # 处理中文/英文冒号
            separator = '：' if '：' in line else ':'
            if separator in line:
                key, value = line.split(separator, 1)
                key = key.strip()
                value = value.strip()

                if key == '类别':
                    # 验证子类别是否在允许的列表中
                    if value in ALL_SUBCATEGORIES:
                        result['子类别'] = value
                        # 确定大类
                        for main_category, subcategories in CLOTHING_CATEGORIES.items():
                            if value in subcategories:
                                result['大类'] = main_category
                                break
                    else:
                        # 尝试从回答中提取有效子类别
                        for subcat in ALL_SUBCATEGORIES:
                            if subcat in value:
                                result['子类别'] = subcat
                                # 确定大类
                                for main_category, subcategories in CLOTHING_CATEGORIES.items():
                                    if subcat in subcategories:
                                        result['大类'] = main_category
                                        break
                                break
                elif key == '季节':
                    # 验证季节是否在允许的列表中
                    if value in SEASONS:
                        result[key] = value
                    else:
                        # 尝试从回答中提取有效季节
                        for season in SEASONS:
                            if season in value:
                                result[key] = season
                                break
                elif key in ['材质', '版型', '颜色']:
                    # 提取简短的词语（最多取前两个词）
                    words = value.split()
                    if words:
                        # 如果回答是句子，尝试提取关键词
                        if len(words) > 2 and len(value) > 10:
                            # 常见的材质关键词
                            material_keywords = ['棉', '麻', '丝', '毛', '皮革', '牛仔', '尼龙', '涤纶', '羊毛', '羊绒',
                                                 '针织',
                                                 '聚酯', '合成', '人造', '真丝', '亚麻', '绒', '绸']
                            # 常见的版型关键词
                            fit_keywords = ['宽松', '修身', '直筒', 'A字', '紧身', '阔腿', '常规', '收腰', '落肩',
                                            '泡泡袖',
                                            '松垮', '紧凑', '贴身', '宽大', '合身']
                            # 常见的颜色关键词
                            color_keywords = ['黑', '白', '灰', '红', '蓝', '绿', '黄', '紫', '粉', '棕', '米', '卡其',
                                              '藏青', '酒红', '淡', '深', '浅', '亮', '暗', '彩']

                            # 根据不同属性选择不同的关键词列表
                            if key == '材质':
                                keywords = material_keywords
                            elif key == '版型':
                                keywords = fit_keywords
                            elif key == '颜色':
                                keywords = color_keywords
                            else:
                                keywords = []

                            # 尝试从句子中提取关键词
                            extracted_words = []
                            for keyword in keywords:
                                if keyword in value:
                                    # 找到关键词所在的位置
                                    pos = value.find(keyword)
                                    # 提取关键词及其前后可能的修饰词（最多5个字符）
                                    start = max(0, pos - 5)
                                    end = min(len(value), pos + len(keyword) + 5)
                                    context = value[start:end]
                                    # 只保留包含关键词的短语（最多10个字符）
                                    if len(context) > 10:
                                        context = context[:10]
                                    extracted_words.append(context)

                            if extracted_words:
                                result[key] = '、'.join(extracted_words[:2])  # 最多取前两个关键词
                            else:
                                # 如果没有找到关键词，取句子的前10个字符
                                result[key] = value[:10] + ('...' if len(value) > 10 else '')
                        else:
                            # 如果回答已经很简短，直接使用
                            result[key] = ' '.join(words[:2])
                    else:
                        result[key] = value

        print("最终解析结果:", result)

        return jsonify({
            "message": "图片分析成功",
            "data": result
        }), 200

    except Exception as e:
        return jsonify({
            "message": f"分析失败: {str(e)}",
            "error_type": type(e).__name__,
        }), 500


# 文件上传接口
@app.route('/api/upload-file', methods=['POST'])
def upload_file():
    try:
        # 检查是否有文件上传
        if 'image' in request.files:
            # 直接从请求中获取文件
            file = request.files['image']
            # 获取文件名
            filename = secure_filename(file.filename)
            # 获取文件类型和用户ID
            file_type = request.form.get('type', 'default')
            user_id = request.form.get('user_id')
        elif request.is_json and 'image' in request.json:
            # 兼容旧的base64方式
            data = request.json
            image_data = base64.b64decode(data['image'])
            file_type = data.get('type', 'default')
            user_id = data.get('user_id')
            # 生成随机文件名

            filename = f"{uuid.uuid4().hex}.jpg"
        else:
            return jsonify({"message": "未上传文件"}), 400

        # 确保上传目录存在
        upload_dir = os.path.join('uploads', file_type)
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)

        # 保存文件
        file_path = os.path.join(upload_dir, filename)

        if 'image' in request.files:
            file.save(file_path)
        else:
            with open(file_path, 'wb') as f:
                f.write(image_data)

        # 构建文件URL
        file_url = f"/uploads/{file_type}/{filename}"

        return jsonify({
            "message": "文件上传成功",
            "file_url": file_url
        }), 200

    except Exception as e:
        return jsonify({
            "message": f"上传失败: {str(e)}",
            "error_type": type(e).__name__,
        }), 500


# 添加静态文件服务
@app.route('/uploads/<path:filename>')
def uploaded_file(filename):
    # 添加调试信息
    print(f"请求文件: {filename}")
    print(f"完整路径: {os.path.join(UPLOAD_FOLDER, filename)}")
    try:
        return send_from_directory(UPLOAD_FOLDER, filename)
    except Exception as e:
        print(f"提供文件时出错: {str(e)}")
        return f"文件访问错误: {str(e)}", 500


# 头像上传专用接口
@app.route('/api/upload-avatar', methods=['POST'])
def upload_avatar():
    try:
        # 检查是否有文件
        if 'file' not in request.files:
            # 尝试从请求体中获取base64编码的图片
            data = request.get_json()
            if data and 'image' in data:
                # 解码base64图片
                image_data = base64.b64decode(data['image'])
                user_id = data.get('user_id')

                if not user_id:
                    return jsonify({"message": "缺少用户ID"}), 400

                # 生成唯一文件名
                filename = f"avatar_{user_id}_{uuid.uuid4().hex}.jpg"
                filepath = os.path.join(UPLOAD_FOLDER, 'avatars', filename)

                # 保存文件
                with open(filepath, 'wb') as f:
                    f.write(image_data)

                # 构建可访问的URL
                file_url = f"/uploads/avatars/{filename}"

                # 更新数据库中的头像URL
                conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
                cursor = conn.cursor()

                update_query = "UPDATE user_info SET file_id = %s WHERE user_id = %s"
                cursor.execute(update_query, (file_url, user_id))
                conn.commit()
                conn.close()

                return jsonify({
                    "message": "头像上传成功",
                    "file_id": file_url
                }), 200
            else:
                return jsonify({"message": "未找到文件"}), 400

        file = request.files['file']
        user_id = request.form.get('user_id')

        if not user_id:
            return jsonify({"message": "缺少用户ID"}), 400

        # 检查文件名是否为空
        if file.filename == '':
            return jsonify({"message": "未选择文件"}), 400

        # 检查文件类型是否允许
        if file and allowed_file(file.filename):
            # 安全地获取文件名并生成唯一文件名
            filename = secure_filename(file.filename)
            unique_filename = f"avatar_{user_id}_{uuid.uuid4().hex}_{filename}"

            # 保存文件
            filepath = os.path.join(UPLOAD_FOLDER, 'avatars', unique_filename)
            file.save(filepath)

            # 构建可访问的URL
            file_url = f"/uploads/avatars/{unique_filename}"

            # 更新数据库中的头像URL
            conn = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
            cursor = conn.cursor()

            update_query = "UPDATE user_info SET file_id = %s WHERE user_id = %s"
            cursor.execute(update_query, (file_url, user_id))
            conn.commit()
            conn.close()

            return jsonify({
                "message": "头像上传成功",
                "file_id": file_url
            }), 200
        else:
            return jsonify({"message": "不允许的文件类型"}), 400

    except Exception as e:
        print(f"头像上传错误: {str(e)}")
        return jsonify({"message": f"头像上传失败: {str(e)}"}), 500


if __name__ == '__main__':
    integrate_recommendation_system(app)
 #   app.run(debug=True)
    app.run(host='0.0.0.0', port=5000, debug=True)